import { Button, Drawer, Form, message, Select } from 'antd';
import React from 'react';
import { NewGuid } from 'ronds-react-ui';
import './index.less';
import MetaFieldsEdit from './components/MetaFieldsEdit';
import MetaPropsEdit from './components/MetaPropsEdit';
import { BASIC_TYPES_OPTIONS } from './constant';

interface IMetadataEditProps {
  onChange?: (data: string) => void;
}

const MetadataEdit = (props: IMetadataEditProps) => {
  const { onChange } = props;

  const [form] = Form.useForm();

  const [metaSchema, setMetaSchema] = React.useState<{ id: string; type: string; properties: any[]; fields?: any[] }>({
    id: '',
    type: '',
    properties: [],
  });
  const [isFields, setIsFields] = React.useState<boolean>(false);
  const [curFields, setCurFields] = React.useState<any>({});

  React.useEffect(() => {
    form.setFieldsValue({ properties: [{ id: 'name', type: 'text' }] });
    form.setFieldsValue({ type: 'object' });
    form.setFieldsValue({ id: NewGuid() });
  }, []);

  const onFinish = (values: any) => {
    console.log('values:', values, JSON.stringify(values));
    const _metaSchema = metaSchema;
    _metaSchema.type = values.type;
    _metaSchema.properties = values.properties;
    setMetaSchema({ ..._metaSchema });
    onChange && onChange(JSON.stringify(_metaSchema));
  };

  const onAddFields = (index: number) => {
    const _properties = form.getFieldValue('properties');

    console.log('properties', _properties);
    const _curFields = _properties[index];
    if (_curFields && _curFields.id) {
      setIsFields(true);
      const idx = (metaSchema?.fields || []).findIndex((v) => v.id === _curFields.id);
      if (metaSchema?.fields && idx >= 0) {
        setCurFields({ ...metaSchema?.fields[idx] });
      } else {
        setCurFields({ ..._curFields });
      }
    } else {
      message.warn(tr('请填写属性名称'));
    }
  };

  const onFieldsChange = (values: any) => {
    const _metaSchema = metaSchema;

    if (_metaSchema.fields) {
      const idx = _metaSchema.fields.findIndex((v) => v.id === values.id);
      if (idx >= 0) {
        _metaSchema.fields[idx] = values;
      } else {
        _metaSchema.fields.push(values);
      }
    } else {
      _metaSchema.fields = [];
      _metaSchema.fields.push(values);
    }

    setMetaSchema({ ..._metaSchema });
    setIsFields(false);
  };

  return (
    <>
      <Form className="metadata-edit" form={form} name="control-hooks" onFinish={onFinish}>
        <Form.Item
          label="类型"
          name="type"
          style={{ marginBottom: '15px' }}
          rules={[
            {
              required: true,
            },
          ]}
        >
          <Select options={BASIC_TYPES_OPTIONS} />
        </Form.Item>

        <MetaPropsEdit form={form} name="properties" onAddFields={onAddFields} />

        <Form.Item>
          <Button type="primary" block htmlType="submit">
            {tr('确定')}
          </Button>
        </Form.Item>
      </Form>

      <Drawer
        title={curFields?.id || 'fields'}
        width={450}
        bodyStyle={{ padding: 0 }}
        placement="right"
        onClose={() => {
          setIsFields(false);
        }}
        mask={false}
        push={false}
        visible={isFields}
        destroyOnClose={true}
      >
        <MetaFieldsEdit key={curFields?.id} id={curFields?.id} defaultValues={curFields} onChange={onFieldsChange} />
      </Drawer>
    </>
  );
};

export default MetadataEdit;
